package com.embhealth.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.embhealth.constant.MessageConstant;
import com.embhealth.dao.*;
import com.embhealth.entity.Result;
import com.embhealth.pojo.*;
import com.embhealth.service.OrderService;
import com.embhealth.utils.DateUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    private AddressDao addressDao;
    @Autowired
    private SetmealDao setmealDao;
    /**
     * 体检预约服务
     * @param map
     * @return
     */
    @Override
    public Result order(Map map) throws Exception {
        //1.获得预约日期
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderDate==null){
            //指定日期没有预约安排
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //预约日期是否约满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations>=number){
            //已经约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //判断用户有无重复预约
        String telephone = (String)map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        //先判断用户是否存在
        if (member!=null){
            Integer memberId = member.getId();//会员id
            Date order_Date=DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//预约套餐
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if (list!=null && list.size()>0){
                //说明用户在重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //如果不是会员
            member=new Member();
            member.setName((String)map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String)map.get("idCard"));
            member.setSex((String)map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }
        //预约成功，更新当前预约人数
        Order order=new Order();
        order.setMemberId(member.getId());//设置会员id
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约时间
        order.setOrderType((String) map.get("ordertype"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String)map.get("setmealId")));//套餐id
        orderDao.add(order);
    // 向预约与体检机构的中间表插入数据
    // 获取体检机构地址对应的id
    System.out.println(map);
        Integer addressId = (Integer) map.get("orderAddress");
        //根据体检机构查询对应的id
        //Integer addressId = addressDao.findAddressIdByAddressDetails(orderAddress);
        //向预约与体检机构的中间表插入数据
        orderDao.insertOrderAndAddress(order.getId(),addressId);
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.updateReservationsByOrderDate(orderSetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    /**
     * 根据id查询预约人信息
     * @param id
     * @return
     */
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        Address address = orderDao.findAddressByOrderId(id);
        if (map!=null){
            Date orderDate =(Date) map.get("orderDate");
            //根据id查询预约地址
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
            map.put("address",address.getAddressDetails());
        }
        return map;
    }

    /**
     * 根据日期和id查询用户预约数据
     * @param starttime
     * @param endtime
     * @param tel
     * @return
     */
    @Override
    public List<Map<String,Object>> findAllOrderByDate(String starttime,String endtime,String tel) throws Exception {
        //查询用户
        Member member = memberDao.findByTelephone(tel);
        Integer memberId = member.getId();
        String name = member.getName();
        List<Map<String,Object>> list=new ArrayList<>();
        List<Order> allOrderByDate = orderDao.findAllOrderByDate(starttime, endtime, memberId);
        //封装套餐信息
        for (Order order : allOrderByDate) {
            //查询套餐信息
            Integer setmealId = order.getSetmealId();
            Setmeal setmeal = setmealDao.findById(setmealId);
            Map<String,Object> map=new HashedMap();
            map.put("id",order.getId());
            map.put("name",name);
            map.put("sex",setmeal.getSex());
            map.put("setmealname",setmeal.getName());
            String date= DateUtils.parseDate2String(order.getOrderDate());
            map.put("date",date);
            list.add(map);
        }
        return list;
    }
    /**
     * 未使用的查询日期方法
     * @param months
     * @return
     */
    public List<Integer> findDate(List<String> months) {
        return  null;
    }
    /**
     * 根据预约id信息封装所有的页面需要数据，请使用Map容器
     * @param id
     * @return
     */
    @Override
    public Map<String,Object> findMapByOrderId(Integer id){
        //初始化容器
        Map<String,Object> map=new HashedMap();
        //先查询对应的预约信息
        Order order = orderDao.findOrderById(id);
        /**封装套餐信息
         * 套餐图片url对应字段为img，
         * 套餐名（name），套餐说明（remark），套餐对应的性别（sex），套餐年龄范围（age）
         */
        //获取套餐id
        Integer setmealId = order.getSetmealId();
        Setmeal setmeal = setmealDao.findById(setmealId);
        map.put("img",setmeal.getImg());
        map.put("name",setmeal.getName());
        map.put("remark",setmeal.getRemark());
        map.put("sex",setmeal.getSex());
        map.put("age",setmeal.getAge());
        /**
         * 预约人，预约方式，预约时间，到诊情况，预约机构地址
         */
        Member member = memberDao.findById(order.getMemberId());
        map.put("membername",member.getName());
        map.put("orderType",order.getOrderType());
        map.put("date",order.getOrderDate());
        map.put("orderStatus",order.getOrderStatus());
        //根据orderid查询预约机构
        Address address = orderDao.findAddressByOrderId(order.getId());
        String adr=address.getAddressDetails()+address.getName();
        map.put("address",adr);
        return map;
    }
}
